package com.uptown.matrix.core.consumer.kafka;

import java.lang.reflect.Method;
import java.time.Duration;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.errors.WakeupException;

@Slf4j
class KafkaConsumerRunnable implements Runnable {

    KafkaConsumer<String, String> consumer;

    Object bean;

    Method method;

    public KafkaConsumerRunnable(KafkaConsumer<String, String> consumer, Object bean, Method method) {
        this.consumer = consumer;
        this.bean = bean;
        this.method = method;
    }

    @Override
    public void run() {

        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(5));
            for (ConsumerRecord<String, String> record : records) {
                try {

                    String value = record.value();
                    method.invoke(bean, value);
                } catch (WakeupException e) {
                    log.info("ignore for shutdown");
                } catch (Exception e) {

                    log.error("kafka message queue deal error", e);
                } finally {

                    consumer.commitAsync();
                }
            }
        }
    }

    public void shutDown() {
        consumer.wakeup();
    }
}